﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;

public partial class uMESAdjustingStockQtyReviewForm : ShopfloorPage, INormalReport
{
    const string QueryWhere = "uMESAdjustingStockQtyReviewForm";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESSecondaryWarehouseBusiness bll = new uMESSecondaryWarehouseBusiness();

    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：库存调整审核";
        master.strTitle = "库存调整审核";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
        normalCntrl.LtnFirst = lbtnFirst;
        normalCntrl.LtnLast = lbtnLast;
        normalCntrl.LtnNext = lbtnNext;
        normalCntrl.LtnPrev = lbtnPrev;
        normalCntrl.BtnReset = btnReSet;
        normalCntrl.BtnGo = btnGo;
        normalCntrl.BtnSearch = btnSearch;
        normalCntrl.LabPages = lLabel1;
        normalCntrl.TxtPage = txtPage;
        normalCntrl.TxtTotalPage = txtTotalPage;
        normalCntrl.TxtCurrentPage = txtCurrentPage;
        normalCntrl.NormalOperation = this;
        normalCntrl.QueryWhere = QueryWhere;

        WebPanel = WebAsyncRefreshPanel1;

        if (!IsPostBack)
        {
            ClearMessage_PageLoad();
        }
    }


    #region 数据查询

    #region 绑定入库原因列表
    protected void GetStockReasonInfo()
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("StockReason", "3");
        DataTable DT = bll.GetStockReasonInfo(para);

        ddlStockReason.DataTextField = "StockReasonName";
        ddlStockReason.DataValueField = "StockReasonId";
        ddlStockReason.DataSource = DT;
        ddlStockReason.DataBind();

        ddlStockReason.Items.Insert(0, "");
    }
    #endregion

    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ClearDispData();
    }
    #endregion
    public Dictionary<string, string> GetQuery()
    {
        string strScanContainerName = txtScan.Text.Trim();
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();

        Dictionary<string, string> result = new Dictionary<string, string>();
        result.Add("ScanContainerName", strScanContainerName);
        result.Add("ProcessNo", strProcessNo);
        result.Add("ContainerName", strContainerName);
        result.Add("ProductName", strProductName);
        result.Add("StartDate", strStartDate);
        result.Add("EndDate", strEndDate);

        //查询未出库库存信息
        result.Add("Out", "1");
        return result;
    }

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";

            if(strScan != string.Empty)
            {
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ScanContainerName", strScan);
                //查询未出库库存信息
                para.Add("Out", "1");
                txtCurrentPage.Text = "1";
                QueryData(para);
            }
        }
        catch(Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    //查询主信息
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.txtCurrentPage.Text = "1";
        Dictionary<string, string> query = GetQuery();
        QueryData(query);
    }

    public void QueryData(Dictionary<string, string> query)
    {
        ClearMessage();
        ClearDispData();
        uMESPagingDataDTO result = bll.GetStockAdjustIngData(query, Convert.ToInt32(this.txtCurrentPage.Text), 10);
        this.ItemGrid.DataSource = result.DBTable;
        this.ItemGrid.DataBind();
        this.txtTotalPage.Text = result.PageCount;
        if (result.RowCount == "0")
        {
            this.txtCurrentPage.Text = "0";
        }
        lLabel1.Text = string.Format("第 {0} 页  共 {1} 页", this.txtCurrentPage.Text, this.txtTotalPage.Text);
        this.txtPage.Text = this.txtCurrentPage.Text;       
    }

    protected void ClearDispData()
    {
        txtDispProcessNo.Text = string.Empty;
        txtDispOprNo.Text = string.Empty;
        txtDispContainerName.Text = string.Empty;
        txtContainerId.Text = string.Empty;
        txtDispProductName.Text = string.Empty;
        txtDispDescription.Text = string.Empty;
        txtProductId.Text = string.Empty;
        txtStockQty.Text = string.Empty;
        txtAfterQty.Text = string.Empty;
        txtAllInQty.Text = "0";
        txtAllOutQty.Text = "0";
        txtUomId.Text = string.Empty;
        txtQty.Text = string.Empty;
        txtFactoryStockID.Text = string.Empty;
        txtReviewComments.Text = string.Empty;
        txtID.Text = string.Empty;
        try
        {
            ddlStockReason.SelectedIndex = 0;
        }
        catch
        {
        }

        ItemGrid.Clear();
       
    }

    public void ResetQuery()
    {
        ClearMessage();

        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        ItemGrid.Rows.Clear();

        this.txtTotalPage.Text = "";
        this.txtCurrentPage.Text = "";
        this.txtPage.Text = "";
        lLabel1.Text = "第  页  共  页";
    }
    #endregion

    #region 分页按钮
    protected void lbtnFirst_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnPrev_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnNext_Click(object sender, EventArgs e)
    {

    }
    protected void lbtnLast_Click(object sender, EventArgs e)
    {

    }
    protected void btnGo_Click(object sender, EventArgs e)
    {

    }
    #endregion
    
    #region 选中批次行
    protected void ItemGrid_ActiveRowChange(object sender, RowEventArgs e)
    {
        ClearMessage();

        try
        {
            txtDispProcessNo.Text = string.Empty;
            if(e.Row.Cells.FromKey("ProcessNo").Value!=null)
            { 
                string strProcessNo = e.Row.Cells.FromKey("ProcessNo").Value.ToString();
                txtDispProcessNo.Text = strProcessNo;
            }

            txtDispOprNo.Text = string.Empty;
            if (e.Row.Cells.FromKey("OprNo").Value != null)
            {
                string strOprNo = e.Row.Cells.FromKey("OprNo").Value.ToString();
                txtDispOprNo.Text = strOprNo;
            }

            string strContainerName = e.Row.Cells.FromKey("ContainerName").Value.ToString();
            txtDispContainerName.Text = strContainerName;

            string strContainerID = e.Row.Cells.FromKey("ContainerID").Value.ToString();
            txtContainerId.Text = strContainerID;

            string strProductName = e.Row.Cells.FromKey("ProductName").Value.ToString();
            txtDispProductName.Text = strProductName;

            txtDispDescription.Text = string.Empty;
            if (e.Row.Cells.FromKey("Description").Value != null)
            {
                string strDescription = e.Row.Cells.FromKey("Description").Value.ToString();
                txtDispDescription.Text = strDescription;
            }

            txtProductId.Text = string.Empty;
            if (e.Row.Cells.FromKey("productid").Value != null)
            {
                string strProductId = e.Row.Cells.FromKey("productid").Value.ToString();
                txtProductId.Text = strProductId;
            }

            txtUomId.Text = string.Empty;
            if (e.Row.Cells.FromKey("uomid").Value != null)
            {
                string strUomId = e.Row.Cells.FromKey("uomid").Value.ToString();
                txtUomId.Text = strUomId;
            }

            //批次数量
            string strQty = string.Empty;
            if (e.Row.Cells.FromKey("qty").Value != null)
            {
               strQty  = e.Row.Cells.FromKey("qty").Value.ToString();
                txtQty.Text = strQty;
            }
            //库存调整原因显示
            GetStockReasonInfo();
            txtStockReasonID.Text = string.Empty;
            {
                txtStockReasonID.Text = e.Row.Cells.FromKey("stockreasonid").Value.ToString();
                ddlStockReason.SelectedValue = txtStockReasonID.Text;
            }

            //分厂二级库
            txtFactoryStockID.Text = string.Empty;
            if (e.Row.Cells.FromKey("FactoryStockID").Value != null)
            {
                txtFactoryStockID.Text = e.Row.Cells.FromKey("FactoryStockID").Value.ToString();
            }

            //库存数量
            txtStockQty.Text=string.Empty;
            if (e.Row.Cells.FromKey("StockQty").Value != null)
            {
                string strStockQty = e.Row.Cells.FromKey("StockQty").Value.ToString();
                txtStockQty.Text = strStockQty;
            }

            //调整后数量 
            txtAfterQty.Text = string.Empty;
            if (e.Row.Cells.FromKey("AfterQty").Value != null)
            {
                string strAfterQty = e.Row.Cells.FromKey("AfterQty").Value.ToString();
                txtAfterQty.Text = strAfterQty;
            }

            txtID.Text = string.Empty;
            if (e.Row.Cells.FromKey("id").Value != null)
            {
                txtID.Text= e.Row.Cells.FromKey("id").Value.ToString();
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #endregion

    #region 按钮事件
    //同意按钮事件
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("Type", "1");
            string strMessage = string.Empty;
            bool result = ProcessData(para, out strMessage);
            DisplayMessage(strMessage, result);
            ClearDispData();

        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    //不同意按钮事件
    protected void btnDis_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("Type", "2");
            string strMessage = string.Empty;
            bool result = ProcessData(para, out strMessage);
            DisplayMessage(strMessage, result);
            ClearDispData();
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected bool ProcessData(Dictionary<string,string> para,out string strMessage)
    {
        ClearMessage();

        bool result = true;
        strMessage = string.Empty;
        
        if (CheckData() == false)
        {
            result = false;
           
        }
        else
        {
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            //事件类型 1=同意调整 2=不统一调整
            string strType = string.Empty;
            if (para.ContainsKey("Type"))
            {
                strType = para["Type"];
            }

            //要修改的信息
            DataTable dtUpdate = new DataTable();
            dtUpdate.Columns.Add("TableName");
            dtUpdate.Columns.Add("ID");
            dtUpdate.Columns.Add("Reviewer");//审核人
            dtUpdate.Columns.Add("ReviewerID");//审核ID
            dtUpdate.Columns.Add("ReviewDate");//审核时间
            dtUpdate.Columns.Add("ReviewComments");//审核意见
            dtUpdate.Columns.Add("Result");//处理结果

            dtUpdate.Rows.Add();
            int intUpdateRow = dtUpdate.Rows.Count - 1;
            dtUpdate.Rows[intUpdateRow]["TableName"] = "inventoryadjustmentinfo";
            dtUpdate.Rows[intUpdateRow]["ID"] = txtID.Text+ "㊣String";
            dtUpdate.Rows[intUpdateRow]["Reviewer"] = userInfo["FullName"] + "㊣String";
            dtUpdate.Rows[intUpdateRow]["ReviewerID"] = userInfo["EmployeeID"] + "㊣String";
            dtUpdate.Rows[intUpdateRow]["ReviewDate"] = DateTime.Now + "㊣Date";
            dtUpdate.Rows[intUpdateRow]["ReviewComments"] = txtReviewComments.Text + "㊣String";

            //不同意调整
            if (strType == "2")
            {
                dtUpdate.Rows[intUpdateRow]["Result"] = "2" + "㊣Integer";
                int iResult = bll.UpdateDataToDatabase(dtUpdate, out strMessage);
                if (iResult == -1)
                {
                    result = false;
                    strMessage = "操作失败！";
                }
                else
                {
                    result = true;
                    strMessage = "操作成功！";
                }

            }
            //同意调整
            else if (strType == "1")
            {
                dtUpdate.Rows[intUpdateRow]["Result"] = "1" + "㊣Integer";
                int iResult = bll.UpdateDataToDatabase(dtUpdate, out strMessage);
                if (iResult == -1)
                {
                    result = false;
                    strMessage = "操作失败！";
                }
                else
                {
                    result = SaveSockInfo();
                    strMessage = "操作成功！";
                    if (result == false)
                    {
                        strMessage = "操作失败！";
                    }


                }
            }
        }
  
        return result;
    }

    protected bool SaveSockInfo()
    {
       bool result = true;
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        //以字典形式传递参数
        Dictionary<string, object> para = new Dictionary<string, object>();
        DataSet ds = new DataSet();
        //返回消息信息
        string strMessage = string.Empty;
        //主表要保存的信息
        DataTable dtMain = new DataTable();
        dtMain.Columns.Add("ID");//唯一标识
        dtMain.Columns.Add("ContainerID");//生产批次ID
        dtMain.Columns.Add("FactoryStockID");//二级库ID
        dtMain.Columns.Add("ProductID");//产品 / 图号ID
        dtMain.Columns.Add("Qty");//批次数量
        dtMain.Columns.Add("UOMID");//计量单位ID
        dtMain.Columns.Add("ContainerName");//生产批次号
        dtMain.Columns.Add("ProductName");//产品 / 图号
        dtMain.Columns.Add("Description");//名称
        dtMain.Columns.Add("ProcessNo");//工作令号
        dtMain.Columns.Add("OprNo");//作业令号
        dtMain.Columns.Add("InQty");//入库数量
        dtMain.Columns.Add("OutQty");//出库数量
        dtMain.Columns.Add("InDate");//最后一次入库时间
        dtMain.Columns.Add("StockQty");//库存数

        //子表要保存的信息
        DataTable dtMine = new DataTable();
        dtMine.Columns.Add("ID");//唯一标识
        dtMine.Columns.Add("ContainerID");//生产批次ID
        dtMine.Columns.Add("FactoryStockID");//二级库ID
        dtMine.Columns.Add("StockReasonID");//出/入库原因ID
        dtMine.Columns.Add("ProductID");//产品/图号ID
        dtMine.Columns.Add("Qty");//出/入数量
        dtMine.Columns.Add("UOMID");//计量单位ID
        dtMine.Columns.Add("EmployeeID");//操作者ID
        dtMine.Columns.Add("OprDate");//操作时间
        dtMine.Columns.Add("Type");//类型
        dtMine.Columns.Add("Notes");//备注
        dtMine.Columns.Add("EmployeeName");//操作者

        //查询主表中是否已添加该批次信息，如果未添加则进行添加，已添加则修改相关信息

        para.Add("ContainerId", txtContainerId.Text);
        DataTable dt1 = bll.GetFactoryStockMainInfo(para);
        if (dt1.Rows.Count > 0)
        {
            DataTable dtUpdate = new DataTable();
            dtUpdate.Columns.Add("TableName");
            dtUpdate.Columns.Add("StockQty");//库存数量

            dtUpdate.Rows.Add();
            int intUpdateRow = dtUpdate.Rows.Count - 1;
            dtUpdate.Rows[intUpdateRow]["TableName"] = "StockInfo";
            dtUpdate.Rows[intUpdateRow]["StockQty"] = txtAfterQty.Text + "㊣String";//库存数量
            int iResult = bll.UpdateDataToDatabase(dtUpdate, out strMessage);
            if (iResult == -1)
            {
                result = false;

            }
        }
        else
        {
            dtMain.Rows.Add();
            int intMainRow = dtMain.Rows.Count - 1;
            dtMain.Rows[intMainRow]["ID"] = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "㊣String"; //唯一标识
            dtMain.Rows[intMainRow]["ContainerID"] = txtContainerId.Text + "㊣String";//生产批次ID
            dtMain.Rows[intMainRow]["FactoryStockID"] = txtFactoryStockID.Text + "㊣String";//二级库ID
            dtMain.Rows[intMainRow]["ProductID"] = txtProductId.Text + "㊣String";//产品 / 图号ID
            dtMain.Rows[intMainRow]["Qty"] = txtQty.Text + "㊣Integer";//批次数量
            dtMain.Rows[intMainRow]["UOMID"] = txtUomId.Text + "㊣String";//计量单位ID
            dtMain.Rows[intMainRow]["ContainerName"] = txtDispContainerName.Text + "㊣String";//生产批次号
            dtMain.Rows[intMainRow]["ProductName"] = txtDispProductName.Text + "㊣String";//产品 / 图号
            dtMain.Rows[intMainRow]["Description"] = txtDispDescription.Text + "㊣String";//名称
            dtMain.Rows[intMainRow]["ProcessNo"] = txtDispProcessNo.Text + "㊣String";//工作令号
            dtMain.Rows[intMainRow]["OprNo"] = txtDispOprNo.Text + "㊣String";//作业令号
            dtMain.Rows[intMainRow]["InQty"] = txtAllInQty + "㊣Integer";//入库数量
            dtMain.Rows[intMainRow]["OutQty"] = txtAllOutQty.Text + "㊣Integer";//出库数量
            dtMain.Rows[intMainRow]["StockQty"] = txtAfterQty + "㊣Integer";
            dtMain.Rows[intMainRow]["InDate"] = DateTime.Now + "㊣Date";

            ds.Tables.Add(dtMain);
            ds.Tables[0].TableName = "StockInfo";

        }

        dtMine.Rows.Add();
        int intMineRow = dtMine.Rows.Count - 1;
        dtMine.Rows[intMineRow]["ID"] = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "㊣String"; //唯一标识
        dtMine.Rows[intMineRow]["ContainerID"] = txtContainerId.Text + "㊣String";//生产批次ID
        dtMine.Rows[intMineRow]["FactoryStockID"] = txtFactoryStockID.Text + "㊣String";//二级库ID
        dtMine.Rows[intMineRow]["StockReasonID"] = ddlStockReason.SelectedValue + "㊣String";//二级库ID
        dtMine.Rows[intMineRow]["ProductID"] = txtProductId.Text + "㊣String";//产品 / 图号ID
        dtMine.Rows[intMineRow]["UOMID"] = txtUomId.Text + "㊣String";//计量单位ID
        dtMine.Rows[intMineRow]["EmployeeID"] = userInfo["EmployeeID"] + "㊣String";//操作者ID
        dtMine.Rows[intMineRow]["EmployeeName"] = userInfo["FullName"] + "㊣String";//操作者
        dtMine.Rows[intMineRow]["OprDate"] = DateTime.Now + "㊣Date";//操作时间
        dtMine.Rows[intMineRow]["Notes"] = "" + "㊣String";//备注
        dtMine.Rows[intMineRow]["Type"] = "1" + "㊣Integer";//1=入库 2=出库 3=冲账入库 4=冲账出库 
        dtMine.Rows[intMineRow]["Qty"] = txtStockQty.Text + "㊣Integer";//操作数量

        //用库存数量与调整后数量进行比较，前者大于后者则进行冲账出库，反之则冲账入库
        if (Convert.ToInt32(txtStockQty.Text) > Convert.ToInt32(txtAfterQty.Text))
        {
            dtMine.Rows[intMineRow]["Type"] = "4" + "㊣Integer";//1=入库 2=出库 3=冲账入库 4=冲账出库 
            dtMine.Rows[intMineRow]["Qty"] = ((Convert.ToInt32(txtStockQty.Text) - Convert.ToInt32(txtAfterQty.Text))).ToString() + "㊣Integer";//操作数量
        }
        else if(Convert.ToInt32(txtStockQty.Text) < Convert.ToInt32(txtAfterQty.Text))
            {
            dtMine.Rows[intMineRow]["Type"] = "3" + "㊣Integer";//1=入库 2=出库 3=冲账入库 4=冲账出库 
            dtMine.Rows[intMineRow]["Qty"] = ((Convert.ToInt32(txtAfterQty.Text)-Convert.ToInt32(txtStockQty.Text))).ToString() + "㊣Integer";//操作数量

        }
        
        ds.Tables.Add(dtMine);
        ds.Tables[ds.Tables.Count - 1].TableName = "StockHistoryInfo";

        para.Add("dsData", ds);

        //保存数据

        result = bll.SaveDataToDatabase(para, out strMessage);

        return result;
    }
    #endregion

    #region 数据验证
    protected Boolean CheckData()
    {
        Boolean result = true;
        return result;
    }
    //验证是否是数字
    public bool IsNumeric(string s)
    {
        bool bReturn = true;
        double result = 0;
        try
        {
            result = double.Parse(s);
        }
        catch
        {
            result = 0;
            bReturn = false;
        }
        return bReturn;
    }

    //验证是否是正整数
    public static bool IsInt(string inString)
    {
        Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
        return regex.IsMatch(inString.Trim());
    }
    #endregion





}